#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/6/8 23:22
# @Author : linjinting
# @Project : custom_protocol
# @File : logger_distribute.py
# @Software: PyCharm


import logging
from TTLLogging import create_logger


class UIHandle(logging.StreamHandler):
    def __init__(self, widget):
        logging.StreamHandler.__init__(self, widget)
        self.formatter = logging.Formatter(
            "[%(asctime)s] [%(levelname)s] %(name)s: %(message)s")

        # self.formatter = logging.Formatter(
        #     "[%(asctime)s] %(levelname)s in %(name)s-%(module)s at %(lineno)d: %(message)s")


class LoggerDistribute(object):
    def __init__(self, logger=None, callback=None):
        if logger is None:
            self.m_logger = create_logger('MsgDistribute.default')
        else:
            self.m_logger = logger

    def add_handle(self, handleClass=None):
        if handleClass:
            handle = handleClass(self)
            self.m_logger.addHandler(handle)

    # def write(self, msg):
    #     try:
    #         self.m_browser.insertPlainText(msg)
    #     except:
    #         pass

    def log(self, **kwargs):
        # print('log', msg, level)
        msg = kwargs.get('msg')
        level = kwargs.get('level', 'None')
        caller = kwargs.get('caller')

        if level == 'info':
            self.m_logger.info(msg)
        elif level == 'debug':
            # msg = msg + 'at %s' % str(caller)
            self.m_logger.debug(msg)
        elif level == 'error':
            msg = msg + '\n------------------------- @ %s' % str(caller)
            self.m_logger.error(msg)
        else:
            return

